import router, { productionMgmRouter,operateRouter } from "@/router";
import store from "./store";
import { Message } from "element-ui";
import { getToken } from "@/utils/auth";
import { transformRoutes } from "@/utils/resetRouter"
import "nprogress/nprogress.css";
import NProgress from "nprogress";
NProgress.configure({ showSpinner: false });
const whiteList = ["/login", '/app-download', '/choose-system'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const hasToken = getToken("token") || '';
  if (hasToken) {
    // 可以判断是否更改过用户信息 比如更改该用户的权限路由
    // 默认为0,刷新时状态初始化1，登录状态改变2，选择基地后状态改变3
    const userStatus = store.getters.status;
    if (userStatus === true || to.path === "/choose-system" || to.path === "/choose-company") {
      next();
      NProgress.done();
    } else {
      try {
        const code = getToken("companyMark");
        if (!code) {
          Message.error("检测到基地身份信息过期，请重新登录！");
          store.dispatch("user/logout");
          router.push('/login');
        } else {
          //跳转路由后改变status状态
          //status状态在页面时Vuex的status置为默认值false;
          //这里我们可以通过status来判断页面当前是否刷新
          store.commit("user/SET_STATUS", true);
          let routerFlag = sessionStorage.getItem('routerFlag')
          let routerList = productionMgmRouter
          if(routerFlag=='OMS'){
            routerList = operateRouter
          }else{
            routerList = productionMgmRouter
          }
          //如果是刷新过来就重新添加路有表
          let add_routers = transformRoutes(routerList)
          router.addRoutes(add_routers);
          next({ ...to, replace: true });
        }
        NProgress.done();
      } catch (error) {
        await store.dispatch("user/resetToken");
        Message.error(error || "Has Error");
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
    console.log(to)

    NProgress.done();
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      Message.warning("登录已过期,请重新登录");
      next(`/login`);
      NProgress.done();
    }
  }
});

router.afterEach((to) => {
  // finish progress bar
  NProgress.done();
  // 多页控制 打开新的页面
  store.dispatch('page/open', to)
});
